#include "CommandSender.h"
#include <QDebug>
#include <QDomDocument>
#include "File/Xml/MacXml.h"
#include "Encrypt/SM4Encrypt.h"
#include "Encrypt/Encrypt.h"
CommandSender::CommandSender(QObject *parent) :
    QObject(parent)
{
    m_cmdId = 0;
    m_isEncrypt = false;
    resendTimer = new QTimer(this);
    resendTimer->setInterval(100);
    connect(resendTimer, SIGNAL(timeout()), this, SLOT(timeoutSlot()));
    resendTimer->start();
}

void CommandSender::registerProtocol(BaseProtocol *protocol)
{
    m_protocolList.append(protocol);
}

void CommandSender::sendCmd(PortStruct target,QSharedPointer<BaseCmd> sharedCmd)
{
    this->handle(target,sharedCmd);
    if(sharedCmd->isResend())
    {
        CmdStruct resendCmd;
        resendCmd.target = target;
        resendCmd.sharedCmd = sharedCmd;
        m_resendMap.insert(sharedCmd->cmdId(),resendCmd);
    }
}

void CommandSender::cancelResend(quint16 cmdId)
{
        m_resendMap.remove(cmdId);
}

bool CommandSender::isEncrypt() const
{
    return m_isEncrypt;
}

void CommandSender::setIsEncrypt(bool isEncrypt)
{
    m_isEncrypt = isEncrypt;
}

void CommandSender::handle(PortStruct target,QSharedPointer<BaseCmd> sharedCmd)
{
    if(!sharedCmd->isHaveCmdId())
    {
        sharedCmd->setCmdId(this->m_cmdId++);
    }
    SM4Encrypt* m4= SM4Encrypt::getInstance();
    sharedCmd->setIsEncrypt(m_isEncrypt);
    Package package = sharedCmd->toPackage();

    //qDebug()<<"type:"<<target.type()<<"name:"<<target.name();
    if(target.type() == "TCPClient" ){
        if(!m4->getIsInit()){
            qDebug()<<"Init SM4 key Fail";
            return;
        }
        qDebug()<<" isInit true seid :"<<m4->getSeId();
        QByteArray body= package.body();
        QVariantMap jsonData;
        jsonData.insert("seId",m4->getSeId());

        jsonData.insert("algorithm","SM4/ECB/PKCS7Padding");
        jsonData.insert("keyAlias","MFMK_SUB");
   //     jsonData.insert("encCert",m4->getSignedCert());
        QJson::Serializer serializer;
        qDebug()<<"functionCode sharedCmd ::::\n"<< sharedCmd->functionCode();
        SM4Encrypt *encrypt = SM4Encrypt::getInstance();
        // qDebug()<<"CommandProcesser::receiveData~~";
        QString str;
        for(int i=0;i<body.size();i++)
        {
            str+=QString("%1").arg((unsigned char)body.at(i),2,16,QLatin1Char('0'))+' ';
        }
        qDebug()<<"body::"<<str;  //打印十六进制数据



        body =encrypt->EncryptBySM4(body);
        jsonData.insert("data",body);
        QByteArray body1 = serializer.serialize(jsonData, NULL);
        package.setBody(body1);
        qDebug()<<"JSON ping jie:   \n"<<body1;
    }


    for(int i=0; i<m_protocolList.size(); i++)
    {

        if(sharedCmd->protocolType() == m_protocolList.at(i)->protocolType())
        {
            if(sharedCmd->protocolType()==ProtocolType::WXTProtocol)
            {
                qDebug()<<"sharedCmd->protocolType()==ProtocolType::WXTProtocol";
                emit postDataSignal(target,package);
            }
            else
            {
                BaseProtocol* protocol = m_protocolList.at(i);
                QByteArray data = protocol->generateData(package);
                emit sendDataSignal(target,data);
            }
        }
    }
}

void CommandSender::timeoutSlot()
{

    foreach (const quint16 &key, m_resendMap.keys())
    {
        QSharedPointer<BaseCmd> sharedCmd = m_resendMap.value(key).sharedCmd;
        PortStruct target = m_resendMap.value(key).target;

        quint32 currentTimeoutCount = sharedCmd->currentTimeoutCount();
        currentTimeoutCount += 100;
        sharedCmd->setCurrentTimeoutCount(currentTimeoutCount);
        if(currentTimeoutCount >= sharedCmd->timeoutCount())
        {
            qDebug()<<"Cmd send timeout,CmdID:" + QString::number(sharedCmd->cmdId(),16)
                      + ",CmdFunctionCode:" + QString::number(sharedCmd->functionCode(),16);
            sharedCmd->setCurrentTimeoutCount(0);
            quint8 resendCount = sharedCmd->reSendCount();
            resendCount--;
            sharedCmd->setReSendCount(resendCount);
            if(resendCount>0)
            {
                handle(target,sharedCmd);
            }
            else
            {
                m_resendMap.remove(key);
                emit cmdTimeoutSignal(target,sharedCmd);
            }
        }
    }
}

void CommandSender::postHttpResult(QByteArray jsonData)
{
    QString mac = "{\"session_id\":";

    mac+="\""+session_id+"\""+", \"lockId\":\"lock1234\"}";

    QString path;
    path="/root/home/6.wav";
     QFile file(path);


     if (!file.open(QIODevice::ReadOnly)) {
         qDebug() << "Fail to read the file!"<<path;
         file.close();
         return ;
     }

     QHttpPart part_file;

     part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"6.wav\""));
     part_file.setBodyDevice(&file);


     QHttpPart part_macAddress;
     part_macAddress.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
     part_macAddress.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"info\""));
     part_macAddress.setBody(mac.toUtf8());

    /* QHttpPart part_fileName;
     part_fileName.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
     part_fileName.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"fileName\""));
     part_fileName.setBody(filename.toUtf8());*/


     QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
     multiPart->append(part_file);
     multiPart->append(part_macAddress);
   //  multiPart->append(part_fileName);

     QNetworkRequest request;
     //request.setUrl(QUrl::fromUserInput("http://192.168.1.210:8087/gateway/UploadGatewayLog"));
     request.setUrl(QUrl::fromUserInput("http://zentao.c-smb.com:18085/interface/identification/result"));

     QNetworkAccessManager naManager ;
     naManager.setNetworkAccessible(QNetworkAccessManager::Accessible);

     QNetworkReply* reply = naManager.post(request, multiPart);
     QEventLoop loop;
     connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
     loop.exec();

     QString replaydata;
     if (reply->error() == QNetworkReply::NoError) {
         replaydata = reply->readAll();
         qDebug()<<"get json success!!!!!!!"<<replaydata;
     } else {
         qDebug()<<"get json false!!!!!!!"<<replaydata;
     }


     multiPart->setParent(reply);
     reply->deleteLater();


     file.close();
}

void CommandSender::postHttpFileRequest(QString mac,QString filename)
{

      int i;
     /*

       QString filename= "1.wav";
        QString mac = "{\"session_id\":";

        mac+="\""+session_id+"\""+", \"voice_index\":\"1\",}";

        QByteArray byte_array = mac.toLatin1();

        qDebug()<<"--postHttpFileRequest  mac="<<mac;
        QFile file("/root/home/1.wav");
        if (!file.open(QIODevice::ReadOnly)) {
            qDebug() << "Fail to read the file!";
            file.close();
            return ;
        }

        QHttpPart part_file;
        part_file.setBodyDevice(&file);
   //     part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\""));


        QHttpPart part_macAddress;
        part_macAddress.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
        part_macAddress.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"info\""));
        part_macAddress.setBody(byte_array);

        QHttpPart part_fileName;
        part_fileName.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
        part_fileName.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"fileName\""));
        part_fileName.setBody(filename.toUtf8());




        QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
        multiPart->append(part_file);
        multiPart->append(part_macAddress);
        multiPart->append(part_fileName);

        QNetworkRequest request;
        //request.setUrl(QUrl::fromUserInput("http://zentao.c-smb.com:18085/interface/voice/training/upload"));
         request.setUrl(QUrl::fromUserInput("http://192.168.1.210:8087/gateway/UploadGatewayLog"));


        QNetworkAccessManager naManager ;
        naManager.setNetworkAccessible(QNetworkAccessManager::Accessible);

        QNetworkReply* reply = naManager.post(request, multiPart);
        QEventLoop loop;
        connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();

        QString replaydata;
        if (reply->error() == QNetworkReply::NoError) {
            replaydata = reply->readAll();
            qDebug()<<"get json success!!!!!!!"<<replaydata;
        } else {
            qDebug()<<"get json false!!!!!!!"<<replaydata;
        }


        multiPart->setParent(reply);
        reply->deleteLater();


        file.close();*/

     for(i=1;i<=1;i++)
     {



    // QString filename= "Basic.xml";
    QString path;
    path="/root/home/systemdata.txt";
       // path="/root/home/systemdata.txt";
     //  path="/root/home/Xml/SceneList.xml";
        //path="/root/home/Xml/Basic.xml";
      //   path="/root/home/Xml/AutomaticList.xml";
       //   path="/root/home/Xml/SavePoint.xml";
    // path="/root/home/Xml/CustomSceneList.xml";
       //   path="/root/home/Log/2024-09-04";
     QFile file(path);


     if (!file.open(QIODevice::ReadOnly)) {
         qDebug() << "Fail to read the file!"<<path;
         file.close();
         return ;
     }

     QHttpPart part_file;
    // part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"2024-09-04\""));
      part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"systemdata.txt\""));
        //  part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"SavePoint.xml\""));
         //    part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"AutomaticList.xml\""));
        // part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"systemdata.txt\""));
        //  part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"SceneList.xml\""));
        //   part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"Basic.xml\""));
     //part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"systemdata.txt\""));
    // else if(i==3)
    // part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"3.wav\""));
    // else if(i==4)
    // part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"4.wav\""));
    // else if(i==5)
    // part_file.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\";filename=\"5.wav\""));
     part_file.setBodyDevice(&file);

     QHttpPart part_macAddress;
     part_macAddress.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
     part_macAddress.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"macAddress\""));
     part_macAddress.setBody(mac.toUtf8());




     QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
     multiPart->append(part_file);
     multiPart->append(part_macAddress);
   //  multiPart->append(part_fileName);

     QNetworkRequest request;
     //request.setUrl(QUrl::fromUserInput("http://47.106.129.185:7079/gateway-tcp-http/gateway/UploadGatewayLog"));
     request.setUrl(QUrl::fromUserInput("http://47.106.129.185:7079/dfs-service/gatewayloginfo/uploadFile"));
     request.setRawHeader("Authorization",("Bearer "+accssToken).toLatin1());
     //request.setUrl(QUrl::fromUserInput("http://zentao.c-smb.com:18085/interface/voice/training/upload"));
      qDebug()<<"Header~~~"<<QString(request.rawHeader("Authorization"));
     QNetworkAccessManager naManager ;
     naManager.setNetworkAccessible(QNetworkAccessManager::Accessible);
    // QObject::connect(naManager, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(requestError(QNetworkReply::NetworkError)));
     QNetworkReply* reply = naManager.post(request, multiPart);
     QEventLoop loop;
     connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
     loop.exec();

     QString replaydata;
     if (reply->error() == QNetworkReply::NoError) {
         replaydata = reply->readAll();
         qDebug()<<"postHttpFileRequest get json success!!!!!!!"<<replaydata;
     } else {
         printf("%d\r\n",reply->error());
         qDebug()<<"postHttpFileRequest get json false!!!!!!!"<<reply->errorString();
     }


     multiPart->setParent(reply);
     reply->deleteLater();


     file.close();
     }
}

void CommandSender::postHttpLogin(QString usrname,QString pwd)
{
    QNetworkRequest request;
    QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    QObject::connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));

    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
    request.setUrl(QUrl::fromUserInput("http://47.106.129.185:7079/registry/user/login"));


    QString str("{\"username\":\"admin\",\"password\":\"lewin808\"}");
    QByteArray byte_array = str.toLatin1();
    qDebug()<<"postHttpLogin "<<str;
    naManager->post(request,byte_array);//发起post请求
}

void CommandSender::postHttpCreate(QByteArray jsonData)
{
    QString mac = "{\"session_id\":";

    mac+="\""+session_id+"\"}";
    /***************** post json array  **************************/
    QNetworkRequest request;
    QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    QObject::connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));

    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
    request.setUrl(QUrl::fromUserInput("http://zentao.c-smb.com:18085/interface/voiceprint/training/create"));

   // QString str("{\"lockId\":\"lock1234\"}");
    QByteArray byte_array = mac.toLatin1();
    qDebug()<<"postHttpCreate "<<mac;
    naManager->post(request,byte_array);//发起post请求
}
void CommandSender::postHttpIdentifi(QByteArray jsonData)
{
    /***************** post json array  **************************/
    QNetworkRequest request;
    QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    QObject::connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));

    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
    request.setUrl(QUrl::fromUserInput("http://zentao.c-smb.com:18085/interface/text/identification/get"));

    QString str("{\"lockId\":\"lock1234\"}");
    QByteArray byte_array = str.toLatin1();
    qDebug()<<"postHttpIdentifi "<<str;
    naManager->post(request,byte_array);//发起post请求
}

void CommandSender::postHttpRequest(QByteArray jsonData)
{
    /***************** post json array  **************************/
    QNetworkRequest request;
    QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    QObject::connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));

    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
    request.setUrl(QUrl::fromUserInput("http://zentao.c-smb.com:18085/interface/text/training/get"));

    QString str("{\"lockId\":\"lock1234\"}");
    QByteArray byte_array = str.toLatin1();
    qDebug()<<"postHttpRequest "<<str;
    naManager->post(request,byte_array);//发起post请求

/***************** post file  **************************/
   /* QString mac = "LEWIN001909281121533330";
    QString filename= "Basic.xml";

    QFile file("/root/home/Xml/Basic.xml");
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Fail to read the file!";
        file.close();
        return ;
    }

    QHttpPart part_file;
    part_file.setBodyDevice(&file);

    QHttpPart part_macAddress;
    part_macAddress.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
    part_macAddress.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"macAddress\""));
    part_macAddress.setBody(mac.toUtf8());

    QHttpPart part_fileName;
    part_fileName.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
    part_fileName.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"fileName\""));
    part_fileName.setBody(filename.toUtf8());


    QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    multiPart->append(part_file);
    multiPart->append(part_macAddress);
    multiPart->append(part_fileName);

    QNetworkRequest request;
    request.setUrl(QUrl::fromUserInput("http://192.168.1.210:8087/gateway/UploadGatewayLog"));


    QNetworkAccessManager naManager ;
    naManager.setNetworkAccessible(QNetworkAccessManager::Accessible);

    QNetworkReply* reply = naManager.post(request, multiPart);
    QEventLoop loop;
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    QString replaydata;
    if (reply->error() == QNetworkReply::NoError) {
        replaydata = reply->readAll();
        qDebug()<<"get json success!!!!!!!"<<replaydata;
    } else {
        qDebug()<<"get json false!!!!!!!"<<replaydata;
    }


    multiPart->setParent(reply);
    reply->deleteLater();


    file.close();*/

}

void CommandSender::replyFinished(QNetworkReply *reply)
{
    allinfo = reply->readAll();
    QByteArray array = allinfo.toLatin1();

    qDebug()<<"get json!!!!!!!"<<allinfo;
  bool ok;
    QJson::Parser parser;
    QVariantMap result = parser.parse(array, &ok).toMap();
    if(ok){
    QVariantMap dataMap = result["data"].toMap();
     accssToken=dataMap["access_token"].toString();
    qDebug()<<"get access_token!!!!!!!"<<accssToken;
    MacXml *macXml = MacXml::getInstance();
     postHttpFileRequest(macXml->mac(),"jj");

    }



}

